package com.example.fooservice;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * TODO
 *
 * @author zhangjun3
 * @date 2022/3/5 00:14
 */
@Component
public class AuthenticationFilter implements GlobalFilter {

    private static final Logger log = LoggerFactory.getLogger(AuthenticationFilter.class);

    @Autowired
    private WebClient.Builder webClientBuilder;

    @Autowired
    @Lazy
    private TokenVerifier tokenVerifier;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 使用 WebClient
        String token = "testString";
        return webClientBuilder.build().get()
                .uri("lb://auth-service/auth/token/verify/" + token)
                .retrieve()
                .bodyToMono(Boolean.class)
                .flatMap(b -> {
                    log.info("call auth service, result={}", b);
                    if (!Boolean.TRUE.equals(b)) {
                        throw new RuntimeException("Invalid token"); // you should throw your own exception
                    }
                    return chain.filter(exchange);
                });

//        // 之前的阻塞调用
//        ResponseEntity<Boolean> result = tokenVerifier.verifyToken(token);
//        // do some check here
//        return chain.filter(exchange);
    }
}
